import {message} from 'antd'

class Ws {
    addConnect(url) {
        // host = host || 'ws://47.107.210.75'
        let wsName = url
        if (this[wsName]) {
            return
        }
        this[wsName] = new WebSocket(url)
        this[wsName].binaryType = 'arraybuffer'
        this[wsName].onopen = (event) => {
            this.onOpen(event, url)
        }
        this[wsName].onerror = (event) => {
            this.onError(event, url)
        }
    }

    deleteConnect(url) {
        if (!this[url]) {
            return
        }
        this[url].close()
        this[url] = null
        console.log(`delete ${url} connect`)

    }

    closeAll() {

    }

    onOpen(event, url) {
        // console.log(event)
    }

    onError(event, url) {
        if (/^\/compare/.test(url)) {
            message.error('比对连接失败，请刷新页面重试！')
        } else if (/^\/grt2018\/unhandled_alarm$/.test(url)) {
            message.error('接收监测结果信息失败，请刷新页面重试！')
        }
        console.log(event);
        console.log(`${url}:connect error!`)
    }
}

const ws = new Ws()

export default ws
